<!--
 * @Author: maomao
 * @Date: 2021-06-28 09:28:42
 * @Description: 
 * @FilePath: \HisDrugWeb\client-app\src\views\drug-corresponding-prescription\drug-corresponding-prescription.vue
-->
<template>
  <div style="display: flex; height: 100%">
    <el-container style="width: 50%; min-width: 640px">
      <el-header style="height: 56px; padding: 0"
        ><div class="head-left">
          <DxToolbar v-bind="toolbarOptions" ref="toolbar">
            <!-- @item-context-menu="rightContext" -->
            <template #word="{ data: word }">
              <p>{{ word }}</p>
            </template>
          </DxToolbar>
        </div>
      </el-header>
      <el-container height="100%">
        <el-aside width="315px" class="aside" height="100%">
          <div class="tips" style="padding-left: 15px">
            <p v-bind="count">尚有211个药品未设置</p>
          </div>
          <Tree
            ref="treeRef"
            v-if="treeData && treeData.length > 0"
            v-bind="treeOptions"
            :items="treeData"
            @item-context-menu="treeItemContext"
            @edit="submitTreeItem"
            @item-click="selectItem"
            v-model:isEditId="treeIsEditId"
            style="padding-left: 15px"
          ></Tree>
          <div class="flex-gray"></div>
        </el-aside>
        <el-container>
          <el-main style="padding-right: 0">
            <div>对应药品</div>
            <div>
              <DxDataGrid
                id="gridContainer"
                :data-source="dataSource"
                :show-borders="true"
                :selected-row-keys="selectedItemKeys"
                @selection-changed="selectionChanged"
                v-bind="DataGridSetting"
              >
                <DxEditing :allow-updating="true" mode="cell" />
                <DxPaging :enabled="false" />
                <DxSelection
                  select-all-mode="allPages"
                  show-check-boxes-mode="onClick"
                  mode="multiple"
                />
                <DxColumn :width="300" data-field="coding" caption="编码" />
                <DxColumn :width="300" data-field="type" caption="药品品种" />
              </DxDataGrid>
            </div>
            <el-footer style="height: 180px; padding-top: 10px">
              <div>
                <DxForm
                  id="form"
                  label-location="left"
                  :form-data="drugModel"
                  @initialized="saveFormInstance"
                  :validation-group="drugValidation"
                  
                >
                  <DxGroupItem caption="设置对应处方" :col-count="10">
                    <DxSimpleItem
                      data-field="pre0"
                      editorType="dxSelectBox"
                      :editor-options="
                        getSelectBoxOptions({
                          displayExpr: 'pre0',
                          valueExpr: 'drugSortId',
                          dataSource: drugSorts0,
                          placeholder:'西药处方签'
                        })
                      "
                      :col-span="4"
                    >
                      <DxLabel text="门诊" />
                    </DxSimpleItem>
                    <DxSimpleItem
                      data-field="drugSopre0rtId"
                      editorType="dxSelectBox"
                      :editor-options="
                        getSelectBoxOptions({
                          displayExpr: 'pre',
                          valueExpr: 'drugSortId',
                          dataSource: drugSorts,
                          placeholder:'中药处方签'
                        })
                      "
                      :col-span="4"
                    >
                      <DxLabel text="住院" />
                    </DxSimpleItem>
                    <DxSimpleItem
                    :col-span="2"
                    >
                      <DxButton
                      text="确定"
                      styling-mode="text"
                      type="default"
                    />
                    </DxSimpleItem>
                  </DxGroupItem>
                </DxForm>
              </div>
            </el-footer>
          </el-main>
        </el-container>
      </el-container>
    </el-container>
    <el-container style="width: 50%" height="100%">
      <el-main>
        <div style="height: 35px; line-height: 15px">对应处方</div>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="门诊(255)" name="first">
            <div>
              <DxDataGrid
                :allow-column-reordering="true"
                :data-source="customers"
                :show-borders="true"
              >
                <DxColumn data-field="coding" caption="编码" />
                <DxColumn data-field="type" caption="药品品种" />
                <DxGroupPanel :visible="true" />
                <DxGrouping :auto-expand-all="autoExpandAll" />
                <DxPaging :page-size="10" />
                <DxSearchPanel :visible="true" />
              </DxDataGrid>
            </div>
          </el-tab-pane>
          <el-tab-pane label="住院(2555)" name="second">
            <DxDataGrid
              :allow-column-reordering="true"
              :data-source="customers"
              :show-borders="true"
            >
              <DxColumn data-field="coding" caption="编码" />
              <DxColumn data-field="type" caption="药品品种" />
              <DxGroupPanel :visible="true" />
              <DxGrouping :auto-expand-all="autoExpandAll" />
              <DxPaging :page-size="10" />
              <DxSearchPanel :visible="true" />
            </DxDataGrid>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts">
import DataSource from "devextreme/data/data_source";
import DxTabs from "devextreme-vue/tabs";
import { dxSelectBoxOptions } from "devextreme/ui/select_box";
import { Options, Vue } from "vue-class-component";
import Tree from "@/framework/components/tree/tree.vue";
import {
  ElContainer,
  ElHeader,
  ElMain,
  ElAside,
  ElIcon,
  ElFooter,
} from "element-plus";
import DxSelectBox from "devextreme-vue/select-box";
import DxTreeView from "devextreme-vue/tree-view";
import DxCheckBox from "devextreme-vue/check-box";
import DxTabPanel from "devextreme-vue/tab-panel";
import { Emit, Inject, Prop, Ref, Watch } from "vue-property-decorator";
import DxButton from "devextreme-vue/button";
import { dxButtonOptions } from "devextreme/ui/button";
import DxToolbar, { DxItem } from "devextreme-vue/toolbar";
import { dxToolbarOptions } from "devextreme/ui/toolbar";
import notify from "devextreme/ui/notify";
import { dxTreeViewOptions } from "devextreme/ui/tree_view";
import { dxDataGridOptions } from "devextreme/ui/data_grid";
import { DxScrollView } from "devextreme-vue/scroll-view";
import {
  DrugClient,
  DrugSortClient,
  DrugSchemeClient,
  DrugSchemeSubmitDTO,
  OutputSearchForDrug,
} from "@/api/api_drugclient";
import {
  DxForm,
  DxSimpleItem,
  DxGroupItem,
  DxTabbedItem,
  DxTabPanelOptions,
  DxTab,
  DxRequiredRule,
  DxLabel,
} from "devextreme-vue/form";
// import { DictionaryClient, DrugSortTree } from "@/api/api_dictionaryclient";
import { ApiExceptionShow } from "@/utils/api-exception-show";
import { ApiTool } from "@/api/api-tool";
import { Tool } from "@/utils/tool";
import { RightContextI } from "@/framework/components/right-menu/right-menu.vue";
import { SearchByURL } from "@/utils/search-byurl";
import { dxTextBoxOptions } from "node_modules/devextreme/ui/text_box";
import { ElTag, ElTabs, ElTabPane } from "element-plus";
import {
  DxDataGrid,
  DxColumn,
  DxPaging,
  DxEditing,
  DxSelection,
  DxLookup,
} from "devextreme-vue/data-grid";
let self: DrugCorrespondingPrescription;
let searchByURL: SearchByURL;
let formData: any = {};
const componentInfo = {
  title: "药品信息",
};
const dataSourceKey = "dictionaryId";
const keyExpr = "drugId";
const getDataGridSetting = function () {
  return {
    height: "calc(100vh - 300px)",
    showBorders: true,
    showColumnLines: false,
    showRowLines: false,
    hoverStateEnabled: true,
    allowColumnResizing: true,
    allowColumnReordering: true,
    remoteOperations: true,
    // rowTemplate:"rowTemplate",
    sorting: {
      mode: "single",
    },
    selection: {
      mode: "single",
    },
    scrolling: {
      mode: "virtual",
      rowRenderingMode: "virtual",
    },
    paging: {
      pageSize: 5,
    },
    keyExpr,
    rowAlternationEnabled: true,
    noDataText: "暂无数据列表，请右键新增药品",
    onToolbarPreparing: (e) => {
      let toolbarItems = e.toolbarOptions.items;
      toolbarItems.length = 0;
    },
    columns: [
      {
        caption: "编码",
        dataField: "coding",
        width: 160,
        // fixed: true,
      },
      {
        caption: "药品品种",
        dataField: "drugName",
        width: 160,
        // fixed: true,
      },
    ],
    editing: {
      allowAdding: false,
      allowDeleting: false,
      allowUpdating: false,
      mode: "popup",
    },
    export: {
      enabled: true,
      allowExportSelectedData: true,
      fileName: componentInfo.title + new Date(),
    },
    onEditingStart(item) {
      formData = item.data;
    },
  } as dxDataGridOptions;
};
@Options({
  components: {
    Tree,
    DxTabPanel,
    DxTabs,
    DxTreeView,
    ElContainer,
    ElHeader,
    ElMain,
    ElAside,
    DxSelectBox,
    DxCheckBox,
    DxDataGrid,
    DxColumn,
    DxEditing,
    DxPaging,
    ElIcon,
    DxToolbar,
    DxItem,
    ElTag,
    DxLabel,
    ElFooter,
    DxSelection,
    DxGroupItem,
    DxButton,
    DxSimpleItem,
    ElTabs,
    DxForm,
    ElTabPane,
  },
})
export default class DrugCorrespondingPrescription extends Vue {
  @Inject()
  formData: any;
  @Inject()
  apiTool: ApiTool;
  client: DrugSortClient;
  client0: DrugSchemeClient;
  readonly menuList: any[] = [];
  searchValue: string;

  @Ref()
  toolbar: DxToolbar;
  @Ref()
  treeRef: Tree;
  tabItemWidth = 100; // tab宽度
  openTab = 0;
  getTabWidth(length) {
    let style = `width:${this.tabItemWidth * length}px`;
    return style;
  }
  treeData: any[] = [];
  treeOptions: dxTreeViewOptions = {
    selectionMode: "single",
  };
  DataGridSetting = getDataGridSetting.call(this);
  // testTreeItem: DrugSortTree = {
  //   drugSortId: "6660",
  //   name: "测试",
  //   parentId: "",
  // };
  beforeUnmount() {
    document.removeEventListener("rightContext", this.rightClick);
  }
  // innerWidth:any
  // getWindowWidth () {
  //   this.innerWidth = window.innerWidth
  //   if (this.innerWidth > 1240) {
  //     this.DataGridSetting.width = this.innerWidth/2 - 315 + 'px'
  //   }else {
  //     this.DataGridSetting.width = '300px'
  //   }
  //   console.log(this.DataGridSetting.width);
  // }
  // 获取目录
  @Watch("drugSchemeId")
  async initTreeData(newVal) {
    if (newVal) {
      this.treeData = await this.getTreeList();
    }
  }

  // 方案id
  get drugSchemeId(): string {
    return (this.$route.query["drugSchemeId"] || "") as string;
  }

  toolbarOptions: dxToolbarOptions = {
    items: [
      {
        location: "before",
        template() {
          return "目录方案";
        },
      },
      {
        options: {
          width: 240,
          items: this.menuList,
          valueExpr: "drugSchemeId",
          displayExpr: "name",
          stylingMode: "outlined",
          placeholder: "请选择",
          onValueChanged: (args) => {
            // 相同不重新赋值,赋值会导致清空其子项
            if (self.drugSchemeId != args.value) {
              searchByURL.setParamsToUrl({ drugSchemeId: args.value });
            }
          },
        },
        location: "before",
        locateInMenu: "auto",
        widget: "dxSelectBox",
      },
      {
        location: "after",
        template() {
          return "显示";
        },
      },
      {
        options: {
          width: 240,
          items: this.menuList,
          valueExpr: "drugSchemeId",
          displayExpr: "name",
          stylingMode: "outlined",
          placeholder: "分类和品种",
          onValueChanged: (args) => {
            // 相同不重新赋值,赋值会导致清空其子项
            if (self.drugSchemeId != args.value) {
              searchByURL.setParamsToUrl({ drugSchemeId: args.value });
            }
          },
        },
        location: "after",
        locateInMenu: "auto",
        widget: "dxSelectBox",
      },
    ],
  };
  // 页面刷新
  refresh() {
    this.$router.replace({ path: "/refresh" });
  }
  searchDrugInfoList: any[] = [];

  setPosition(item: OutputSearchForDrug | any) {
    let params = {
      drugSortId: item.sort,
      drugId: item.drugInfo.drugId,
    };
    searchByURL.setParamsToUrl(params);
  }

  // selectBox回显数据
  setDrugSchemeId(drugSchemeId) {
    self.toolbar.instance.option("items[1].options.value", drugSchemeId);
    // searchByURL.setParamsToUrl({ drugSchemeId });
  }
  created() {
    self = this;
    searchByURL = new SearchByURL(this.$router);
    this.client = this.apiTool.createClient(DrugSortClient);
    this.client0 = this.apiTool.createClient(DrugSchemeClient);
    // window.addEventListener('resize', this.getWindowWidth);
    // this.getWindowWidth()
  }
  async mounted() {
    document.addEventListener("rightContext", this.rightClick);
    this.treeData = await this.getTreeList();
    let drugSchemeId = (this.$route.query.drugSchemeId || "") as string;
    // document.addEventListener("rightContext", this.rightClick);
    let list = await this.getMenuList();
    Tool.constArrayAssignment(this.menuList, list);
    if (list.length) {
      // 回显
      if (this.drugSchemeId) {
        this.setDrugSchemeId(drugSchemeId);
      }
      // 默认第一条
      else {
        this.setDrugSchemeId(list[0].drugSchemeId);
        searchByURL.setParamsToUrl({ drugSchemeId: list[0].drugSchemeId });
      }
    }
  }

  // 根据方案id获取目录
  getTreeList() {
    if (!this.drugSchemeId) return null;
    return this.client.getListPageWithDrugSchemeId(this.drugSchemeId).then(
      (res) => {
        if (res.isSuccess) {
          let drugSortId = this.drugSortId;
          let parentId = "";
          if (res.listData.length > 0 && !drugSortId) {
            parentId = res.listData[0].parentId;
            drugSortId = res.listData[0].drugSortId;
            searchByURL.setParamsToUrl({
              drugSortId,
              parentId,
            });
          }
          let listData = this.treeListChangeSelect(drugSortId, res.listData);
          return listData;
        } else {
          notify(res.message, "error");
          return [];
        }
      },
      (err) => {
        ApiExceptionShow.showException(err, this);
        return [];
      }
    );
  }
  // 正在编辑的treeItemID
  treeIsEditId = "";
  // 药品数目录操作菜单
  rightMenu: any = [
    {
      text: "新增",
      id: "add",
      items: [
        {
          text: "同级分类",
          id: "addBrother",
        },
        {
          text: "子级分类",
          id: "addChild",
        },
      ],
    },
    {
      id: "edit",
      text: "修改",
    },
    {
      id: "remove",
      text: "删除",
    },
    {
      id: "print",
      text: "打印",
      items: [
        {
          id: "money",
          text: "价目表",
        },
        {
          id: "typeList",
          text: "品种清单",
        },
      ],
    },

    {
      id: "enable",
      text: "启用",
    },
    {
      id: "disable",
      text: "禁用",
    },
    {
      text: "显示",
      id: "show",
      items: [
        {
          id: "showDurgNum",
          text: "药品数量",
          radioGroup: "showNum",
        },
        {
          id: "showSku",
          text: "规格数量",
          radioGroup: "showNum",
        },
        {
          id: "showAbled",
          text: "启用",
          isCheckBox: true,
          value: true,
        },
        {
          id: "showDisabled",
          text: "停用",
          isCheckBox: true,
          value: false,
        },
      ],
    },
  ];
  @Inject()
  rightContextOption: RightContextI;
  // 右键菜单初始化
  rootValue = "00000000-0000-0000-0000-000000000000";
  treeItemContext(e) {
    this.rightContextOption.content = {
      id: "drugTree",
      event: e,
    };
    let { isEdit, type } = e;
    let rightMenu = this.rightMenu;
    // 顶级菜单
    if (e.parentId == this.rootValue) {
      rightMenu[0].items[0]["disabled"] = true;
    } else {
      rightMenu[0].items[0]["disabled"] = false;
    }
    // 是否允许编辑
    if (isEdit) {
      rightMenu = this.rightMenu.map((item) => {
        return {
          ...item,
          disabled: item.id == "edit" || item.id == "remove",
        };
      });
    }
    // 未分类
    rightMenu[0].items[1]["disabled"] = type == 4;
    this.rightContextOption.items = rightMenu;
  }
  // 右键菜单被点击
  rightClick(event: CustomEvent) {
    let { detail = {} } = event;
    let { itemData, content } = detail;
    if (content.id != "drugTree") {
      return;
    }
    let { coding, drugSchemeId, drugSortId, name, parentId } = content.event;
    switch (itemData.id) {
      case "addBrother":
        this.addTreeItem({
          drugSchemeId,
          parentId,
          name: "",
          drugSortId: "",
        });
        break;
      case "addChild":
        this.addTreeItem({
          drugSchemeId,
          parentId: drugSortId,
          name: "",
          drugSortId: "",
        });
        this.expandItem(drugSortId);
        break;
      case "edit":
        this.treeIsEditId = drugSortId;
        break;
      case "remove":
        this.client.delete(drugSortId).then(
          (res) => {
            if (res.isSuccess) {
              let parent = this.treeData.find((item) => {
                if (item.drugSortId == parentId) {
                  return item;
                }
              });
              searchByURL.setParamsToUrl({
                drugSortId: parentId,
                parentId: parent.drugSortId,
              });
              notify(res.message, "success");
              this.getTreeList().then((data) => {
                this.treeData = data;
              });
            } else {
              notify(res.message, "error");
            }
          },
          (err) => {
            ApiExceptionShow.showException(err, this);
          }
        );
        break;
      default:
        break;
    }
  }
  // 提交tree表单
  submitTreeItem(item) {
    if (!item.value) {
      // 添加且未输入名称删除添加item
      if (!item.data.drugSortId) {
        this.treeData = [].concat(this.deleteTreeItem(""));
      }
      return;
    }
    this.client
      .submit({
        ...item.data,
        name: item.value,
        drugSchemeId: this.drugSchemeId,
      })
      .then(
        async (res) => {
          if (res.isSuccess) {
            searchByURL.setParamsToUrl({
              drugSortId: res.data,
              parentId: item.data.parentId,
            });
            notify(res.message, "success");
            this.treeData = await this.getTreeList();
          } else {
            notify(res.message, "error");
          }
        },
        (err) => {
          ApiExceptionShow.showException(err, this);
        }
      );
  }
  // 删除数组单个元素
  deleteTreeItem(drugSortId: string, list = this.treeData) {
    console.log();

    list.forEach((ele, index) => {
      if (ele.drugSortId == drugSortId) {
        list.splice(index, 1);
      }
    });
    return list;
  }
  // tree添加按钮配置
  addTreeItemOptions: dxButtonOptions = {
    text: "新建目录",
    stylingMode: "contained",
    type: "default",
    onClick: () => {
      if (!self.drugSchemeId) {
        notify("请先选择方案");
        return;
      }
      self.addTreeItem({
        drugSchemeId: self.drugSchemeId,
        parentId: self.rootValue,
        name: "",
        drugSortId: "",
      });
    },
  };
  // 本地添加数据
  addTreeItem(addItem) {
    let treeData = this.treeData || [];
    treeData.splice(treeData.length, 0, addItem);
    this.treeData = Object.assign([], treeData);
  }

  // 选中item drugSortId
  get drugSortId(): string {
    return (this.$route.query.drugSortId || "") as string;
  }
  // 初始化选择
  @Watch("drugSortId")
  initSelect(newVal) {
    this.treeData = this.treeListChangeSelect(newVal, this.treeData);
  }
  // 选中item
  selectItem(item) {
    let itemData = item.itemData;
    let { drugSortId = "", parentId = "", type = "" } = itemData;
    searchByURL.setParamsToUrl({
      drugType: type,
      drugSortId,
      parentId,
      filterCoding: "",
      filterName: "",
      filterDrugShortCode: "",
    });
    // this.treeData = this.treeListChangeSelect(drugSortId);
  }
  // 修改列表选中
  treeListChangeSelect(drugSortId: string, listData = this.treeData) {
    if (drugSortId) {
      listData = listData.map((item) => {
        if (item.drugSortId == drugSortId) {
          item["selected"] = true;
        } else {
          item["selected"] = false;
        }
        return item;
      });
    }
    listData = this.treeListExpand(drugSortId, listData);
    return listData;
  }

  getSelectBoxOptions(extendOptions: dxSelectBoxOptions): dxSelectBoxOptions {
    return Object.assign({}, this.tagSetting, extendOptions);
  }
  tagSetting: dxSelectBoxOptions = {
    stylingMode: "outlined",
    showDropDownButton: true,
  };
  // 展开指定目录
  expandItem(id: string) {
    this.treeData = this.treeData.map((item) => {
      if (item.drugSortId == id) {
        item.expanded = true;
      }
      return item;
    });
  }
  // 数据驱动展开列表
  treeListExpand(drugSortId: string, listData = this.treeData) {
    if (drugSortId) {
      let parents = Tool.getTreeParentsById(listData, {
        key: "drugSortId",
        id: drugSortId,
        parentKey: "parentId",
        rootValue: this.rootValue,
      });
      for (let item of listData) {
        item.expanded = false;
        for (let parn of parents) {
          if (parn.drugSortId == item.drugSortId) {
            item.expanded = true;
          }
        }
      }
    }
    return listData;
  }
  // 获取方案列表
  getMenuList() {
    return this.client0
      .page({
        index: 0,
        pageSize: 100,
      })
      .then(
        (res) => {
          if (res.isSuccess) {
            return res.listData;
          } else {
            notify(res.message, "error", 2000);
            return [];
          }
        },
        (err) => {
          ApiExceptionShow.showException(err, this);
          return [];
        }
      );
  }
  // 添加方案
  addMenu(item: DrugSchemeSubmitDTO) {
    this.client0.submit(item).then((res) => {
      if (res.isSuccess) {
        notify(res.message || "添加成功", "success", 2000);
      }
    });
  }
}
</script>

<style scoped lang="scss">
.head-left {
  padding-left: 15px;
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
}
.tips {
  width: 100%;
  height: 30px;
  color: #555;
  text-align: center;
  line-height: 20px;
  p {
    padding: 10px 0;
  }
}
.aside {
  position: relative;
  border-right: 1px solid #ccc;
  margin-right: -1px;
  .flex-gray {
    width: 100%;
    position: absolute;
    top: 210px;
    bottom: 0;
    background-color: #ccc;
  }
}
#data-grid-demo {
  min-height: 700px;
}

#gridDeleteSelected {
  position: absolute;
  z-index: 1;
  right: 0;
  margin: 1px;
  top: 0;
}

#gridDeleteSelected .dx-button-text {
  line-height: 0;
}
</style>
